package org.utils.net;

import java.io.IOException;

/**
 * @author eveno
 *
 */
public class WindowsNetworkInfo extends NetworkInfo
{
    public static final String IPCONFIG_COMMAND = "ipconfig /all";

	/**
	 * 
	 */
	public WindowsNetworkInfo()
	{
		super();
	}

	/**
	 * @see org.utils.net.NetworkInfo#getMacAddress()
	 */
	public String getMacAddress() throws IOException
	{
		// run command
		String ipConfigResponse = runConsoleCommand(IPCONFIG_COMMAND);

		// get localhost address
		String localHost = NetworkUtils.getIPAdress();

		java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(ipConfigResponse, "\n");
		String lastMacAddress = null;
		while (tokenizer.hasMoreTokens())
		{
			String line = tokenizer.nextToken().trim();

			// see if line contains IP address, this means stop if we've already seen a MAC address
			if (line.endsWith(localHost) && lastMacAddress != null)
			{
				return lastMacAddress;
			}

			// see if line might contain a MAC address
			int macAddressPosition = line.indexOf(":");
			if (macAddressPosition <= 0)
			{
				continue;
			}

			// trim the line and see if it matches the pattern
			String macAddressCandidate = line.substring(macAddressPosition + 1).trim();
			if (isMacAddress(macAddressCandidate))
			{
				lastMacAddress = macAddressCandidate;
				continue;
			}
		}
		throw new IOException("Cannot read MAC address from [" + ipConfigResponse + "]");
	}
}
